﻿using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace Acme.BookStore.Authors
{
    public class AuthorManager:DomainService
    {
        IAuthorRepository _authorRepository;

        public AuthorManager(IAuthorRepository authorRepository)
        {
            _authorRepository = authorRepository;
        }

        public async Task<Author> CreateAsync([NotNull] string name, DateTime birthDate, [CanBeNull] string shortBio = null)
        {
            Check.NotNullOrWhiteSpace(name, nameof(name), AuthorConsts.MaxNameLength);
            if(await _authorRepository.FindByNameAsync(name) != null)
            {
                throw new AuthorAlreadyExistsException(name);
            }
            var author = new Author(GuidGenerator.Create(),name, birthDate, shortBio);
            return author;
        }

        public async Task ChangeNameAsync([NotNull] Author author, [NotNull] string newName)
        {
            Check.NotNull(author, nameof(author));
            Check.NotNullOrWhiteSpace(newName, nameof(newName));
            if (newName != author.Name)
            {
                var existAuthor = await _authorRepository.FindByNameAsync(newName);
                if(existAuthor!=null && existAuthor.Id != author.Id)
                {
                    throw new AuthorAlreadyExistsException(newName);
                }
                author.ChangeName(newName);
            }
            
        }

    }
}
